package ljt.music.widget;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.ljt.bulr.BlurUtils;
import ljt.music.R;
import ljt.music.adapter.BasePagerAdapter;
import ljt.music.bean.LyricBean;
import ljt.music.bean.URLBean;
import ljt.music.request.ApiService;
import ljt.music.service.PlayUtils;
import ljt.music.utils.Download;
import ljt.music.utils.PermissionUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author jiangtao
 * @date 2017/9/18
 */
@SuppressWarnings("ResourceType")
public class PlayDialog implements View.OnClickListener {

  private TextView tv_start;
  private TextView tv_duration;
  private SeekBar seekbar;
  private boolean isDrag;
  private TextView name;
  private TextView author;
  private CircleImageView circleImageView;
  private ImageView back;
  private ImageView backgroundImage;
  private String TAG = "DetailActivity";
  private ImageView controller;
  private URLBean urlBean;
  private LyricBean lyricBean;
  private ImageView download;
  private TextView switch_res;
  private String intentId;
  private String intentName;
  private String intentSubtitle;
  private String intentUrl;
  private Activity activity;
  private Dialog overLayDialog;
  public static final String MUSIC_RECEIVER_ACTION = "MUSIC_RECEIVER_ACTION";
  private AnimatorSet set;
  private Bitmap iconBitmap;
  private BasePagerAdapter adapter;
  private ViewPager viewPager;
  private ArrayList<Fragment> fragmentList;
  private TextView lyric;

  private String REGEX = "\\[[0-5][0-9]:[0-5][0-9].([0-9][0-9]|[0-9][0-9][0-9])\\]";

  public void showDialog() {
    initView();
    initData("netease");
    registerReceiver();
  }

  public PlayDialog(Activity activity, String name, String id, String subtitle, String url) {
    this.activity = activity;
    intentName = name;
    intentId = id;
    intentSubtitle = subtitle;
    intentUrl = url;
  }

  private void initView() {
    View view = View.inflate(activity, R.layout.full_screen_dialog, null);

    overLayDialog = new MusicDialog(activity, R.style.dialogFullscreen);
    overLayDialog.setContentView(view);

    Window window = overLayDialog.getWindow();
    window.setWindowAnimations(R.style.dialogOverlayAnimation);

    overLayDialog.setCancelable(false);
    overLayDialog.show();

    back = view.findViewById(R.id.back);
    backgroundImage = view.findViewById(R.id.backgroundImage);

    name = view.findViewById(R.id.name);
    author = view.findViewById(R.id.author);
    circleImageView = view.findViewById(R.id.circleImageView);
    lyric = view.findViewById(R.id.lyric);

    tv_start = view.findViewById(R.id.tv_start);
    tv_duration = view.findViewById(R.id.tv_duration);

    seekbar = view.findViewById(R.id.seekbar);


    circleImageView.setOnClickListener(this);
    lyric.setOnClickListener(this);
    back.setOnClickListener(this);

    set = new AnimatorSet();
    ObjectAnimator rotation = ObjectAnimator.ofFloat(circleImageView, "rotation", 0f, 360f);
    rotation.setDuration(5000);//设置动画时间
    rotation.setInterpolator(new LinearInterpolator());//设置动画插入器，
    rotation.setRepeatCount(-1);//设置动画重复次数，这里-1代表无限
    rotation.setRepeatMode(Animation.INFINITE);//设置动画循环模式。

    set.play(rotation);
    set.start();

    controller = view.findViewById(R.id.controller);
    controller.setOnClickListener(this);
    controller.setImageResource(R.drawable.image_btn_pause);

    download = view.findViewById(R.id.download);
    download.setOnClickListener(this);

    switch_res = view.findViewById(R.id.switch_res);
    switch_res.setOnClickListener(this);

    name.setText(intentName);
    author.setText(intentSubtitle);


    SimpleTarget<Bitmap> simpleTarget = new SimpleTarget<Bitmap>() {
      @Override
      public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
        iconBitmap = resource;
        circleImageView.setImageBitmap(resource);
        Bitmap newBitmap = BlurUtils.doBlur(resource, 1, 60);
        backgroundImage.setImageBitmap(newBitmap);
      }
    };

    if (intentUrl != null) {
      Glide.with(activity)
          .load(intentUrl)
          .asBitmap()
          .into(simpleTarget);
    }

//    try {
//      Bitmap bitmap = Glide.with(activity)
//          .load(intentUrl)
//          .asBitmap()
//          .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
//          .get();
//      Log.i(TAG, "" + bitmap);
//      activity.runOnUiThread(() -> {
//        backgroundImage.setImageBitmap(blur(bitmap, 25f));
//      });
//    } catch (Exception e) {
//      e.printStackTrace();
//    }

  }

  private static void postDelayIntoMain(final Dialog overLayDialog, long delayTime) {
    new Handler().postDelayed(overLayDialog::dismiss, delayTime);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.back:
        overLayDialog.dismiss();
        break;
      case R.id.controller:
        if (urlBean == null) {
          return;
        }
        play("PLAYING");
        break;
      case R.id.download:
        if (PermissionUtils.applyStoragePermission(activity)) {
          dialogNormal();
        }
        break;
      case R.id.switch_res:
        dialogList();
        break;
      case R.id.circleImageView: {
        Log.i("TAG", "click circleImageView");

        circleImageView.setClickable(false);
        lyric.setClickable(true);

        AnimatorSet set = new AnimatorSet();
        ObjectAnimator alpha = ObjectAnimator.ofFloat(circleImageView, "alpha", 1, 0);
        alpha.setDuration(500);
        alpha.setInterpolator(new AccelerateInterpolator());
        alpha.setRepeatCount(0);
        alpha.setRepeatMode(Animation.ABSOLUTE);

        ObjectAnimator alpha1 = ObjectAnimator.ofFloat(lyric, "alpha", 0, 1);
        alpha1.setDuration(500);
        alpha1.setInterpolator(new AccelerateInterpolator());
        alpha1.setRepeatCount(0);
        alpha1.setRepeatMode(Animation.ABSOLUTE);
        set.play(alpha)
            .with(alpha1);
        set.addListener(new Animator.AnimatorListener() {
          @Override
          public void onAnimationStart(Animator animation) {

          }

          @Override
          public void onAnimationEnd(Animator animation) {
            circleImageView.setVisibility(View.GONE);
            lyric.setVisibility(View.VISIBLE);
          }

          @Override
          public void onAnimationCancel(Animator animation) {

          }

          @Override
          public void onAnimationRepeat(Animator animation) {

          }
        });
        set.start();
        break;
      }
      case R.id.lyric: {
        Log.i("TAG", "click lyric");

        circleImageView.setClickable(true);
        lyric.setClickable(false);

        AnimatorSet set = new AnimatorSet();
        ObjectAnimator alpha = ObjectAnimator.ofFloat(circleImageView, "alpha", 0, 1);
        alpha.setDuration(500);
        alpha.setInterpolator(new AccelerateInterpolator());
        alpha.setRepeatCount(0);
        alpha.setRepeatMode(Animation.ABSOLUTE);

        ObjectAnimator alpha1 = ObjectAnimator.ofFloat(lyric, "alpha", 1, 0);
        alpha1.setDuration(500);
        alpha1.setInterpolator(new AccelerateInterpolator());
        alpha1.setRepeatCount(0);
        alpha1.setRepeatMode(Animation.ABSOLUTE);
        set.play(alpha)
            .with(alpha1);
        set.addListener(new Animator.AnimatorListener() {
          @Override
          public void onAnimationStart(Animator animation) {

          }

          @Override
          public void onAnimationEnd(Animator animation) {
            circleImageView.setVisibility(View.VISIBLE);
            lyric.setVisibility(View.GONE);
          }

          @Override
          public void onAnimationCancel(Animator animation) {

          }

          @Override
          public void onAnimationRepeat(Animator animation) {

          }
        });
        set.start();
        break;
      }
      default:
    }
  }

  private void dialogNormal() {

    DialogInterface.OnClickListener dialogOnclicListener = (dialog, which) -> {
      switch (which) {
        case Dialog.BUTTON_POSITIVE:
          Toast.makeText(activity, "确认",
              Toast.LENGTH_SHORT).show();
          download();
          break;
        case Dialog.BUTTON_NEGATIVE:
          Toast.makeText(activity, "取消",
              Toast.LENGTH_SHORT).show();
          break;
        case Dialog.BUTTON_NEUTRAL:
          Toast.makeText(activity, "忽略",
              Toast.LENGTH_SHORT).show();
          break;
        default:
      }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(activity, 3);
    builder.setIcon(R.mipmap.ic_launcher);
    builder.setTitle("普通对话框");
    builder.setMessage("是否 下载?");
    builder.setPositiveButton("确认", dialogOnclicListener);
    builder.setNegativeButton("取消", dialogOnclicListener);
    builder.setNeutralButton("忽略", dialogOnclicListener);
    builder.create().show();
  }

  private void download() {
//    DownloadUtils downloadUtils = new DownloadUtils(activity);
//    downloadUtils.downloadAPK(intentName + "-" + intentSubtitle,
//        intentName + "-" + intentSubtitle, "正在下载 " + intentName + "-" + intentSubtitle + "...",
//        Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "DownloadMp3",
//        urlBean.getUrl());
    new Download(activity, intentName + "-" + intentSubtitle, iconBitmap).execute(urlBean.getUrl());
  }

  private void dialogList() {
    final String items[] = {"网易", "腾讯", "虾米", "酷狗", "百度"};

    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setTitle("列表");
    // builder.setMessage("是否确认退出?"); //设置内容
    builder.setIcon(R.mipmap.ic_launcher);
    // 设置列表显示，注意设置了列表显示就不要设置builder.setMessage()了，否则列表不起作用。
    builder.setItems(items, new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
        Toast.makeText(activity, items[which],
            Toast.LENGTH_SHORT).show();
        if (items[which].equals("网易")) {
          initData("netease");
        } else if (items[which].equals("腾讯")) {
          initData("tencent");
        } else if (items[which].equals("虾米")) {
          initData("xiami");
        } else if (items[which].equals("酷狗")) {
          initData("kugou");
        } else if (items[which].equals("百度")) {
          initData("baidu");
        }

      }
    });
    builder.setPositiveButton("确定", (dialog, which) -> {
      dialog.dismiss();
      Toast.makeText(activity, "确定", Toast.LENGTH_SHORT)
          .show();
    });
    builder.create().show();
  }

  void play(String action) {
    Intent intent = new Intent(action);
    activity.sendBroadcast(intent);
  }

  private static final String BASE_URL = "http://yyk.zzbssb.com/";
  private Call<URLBean> callURLBean;
  private Call<LyricBean> callLyricBean;

  public void request(String id, String types, String source, Callback<URLBean> callback) {
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
//                .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .build();

    ApiService apiService = retrofit.create(ApiService.class);
    Map<String, Object> map = new HashMap<>();
    map.put("types", types);
    map.put("id", id);
    map.put("source", source);
    callURLBean = apiService.queryURLBean(map);
    callURLBean.enqueue(callback);
  }

  public void requestLyric(String id, String types, String source, Callback<LyricBean> callback) {
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
//                .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .build();

    ApiService apiService = retrofit.create(ApiService.class);
    Map<String, Object> map = new HashMap<>();
    map.put("types", types);
    map.put("id", id);
    map.put("source", source);
    callLyricBean = apiService.queryLyricBean(map);
    callLyricBean.enqueue(callback);
  }

  private void initData(String source) {
    request(intentId, "url", source, new Callback<URLBean>() {
      @Override
      public void onResponse(Call<URLBean> call, Response<URLBean> response) {
        if (response.isSuccessful()) {
          urlBean = response.body();
          PlayUtils.startPlayMp3(activity, urlBean.getUrl());
          controller.setClickable(true);
        } else {
          Toast.makeText(activity, "暂无数据", Toast.LENGTH_SHORT).show();
        }
      }

      @Override
      public void onFailure(Call<URLBean> call, Throwable t) {
        Toast.makeText(activity, "请求失败", Toast.LENGTH_SHORT).show();
        Log.e(TAG, t.toString());
      }
    });

    requestLyric(intentId, "lyric", source, new Callback<LyricBean>() {
      @Override
      public void onResponse(Call<LyricBean> call, Response<LyricBean> response) {
        if (response.isSuccessful()) {
          lyricBean = response.body();
          lyric.setText(lyricBean.getLyric().replaceAll(REGEX,""));
        }
      }

      @Override
      public void onFailure(Call<LyricBean> call, Throwable t) {

      }
    });
  }

  private void registerReceiver() {
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(MUSIC_RECEIVER_ACTION);
    activity.getApplicationContext().registerReceiver(musicBroadcastReceiver, intentFilter);
  }

  MusicBroadcastReceiver musicBroadcastReceiver = new MusicBroadcastReceiver();

  class MusicBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if (action.equals(MUSIC_RECEIVER_ACTION)) {
        int percent = intent.getIntExtra("percent", 0);
        int currentPosition = intent.getIntExtra("CurrentPosition", 0);
        int duration = intent.getIntExtra("Duration", 0);
        boolean isPlaying = intent.getBooleanExtra("isPlaying", false);

        Log.i("TAG", "percent:" + percent);
        Log.i("TAG", "CurrentPosition:" + currentPosition);
        Log.i("TAG", "isPlaying:" + isPlaying);
        Log.i("TAG", "Duration:" + duration);

        int durationS = duration / 1000;
        int currentPositionS = currentPosition / 1000;
        int durationM = 0;
        int currentPositionM = 0;
        if (currentPositionS >= 60) {
          currentPositionM = currentPositionS / 60;
          currentPositionS = currentPositionS % 60;
        }
        if (durationS >= 60) {
          durationM = durationS / 60;
          durationS = durationS % 60;
        }
        tv_start.setText(currentPositionM + ":" + (currentPositionS < 10 ? "0" + currentPositionS : currentPositionS));
        tv_duration.setText(durationM + ":" + (durationS < 10 ? "0" + durationS : durationS));

        seekbar.setMax(duration);
        seekbar.setProgress(currentPosition);
        seekbar.setSecondaryProgress(percent);
//        seekbar.setThumb(activity.getDrawable(R.drawable.ic_launcher_background));
        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
          @Override
          public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (isDrag) {
              Intent intent = new Intent("PROGRESS");
              intent.putExtra("progress", progress);
              activity.sendBroadcast(intent);
            }
          }

          @Override
          public void onStartTrackingTouch(SeekBar seekBar) {
            isDrag = true;
          }

          @Override
          public void onStopTrackingTouch(SeekBar seekBar) {
            isDrag = false;
          }
        });
        if (isPlaying) {
          controller.setImageResource(R.drawable.image_btn_pause);
        } else {
          controller.setImageResource(R.drawable.image_btn_play);
        }
      }
    }
  }

  class MusicDialog extends Dialog {
    public MusicDialog(@NonNull Context context) {
      super(context);
    }

    public MusicDialog(@NonNull Context context, int themeResId) {
      super(context, themeResId);
    }

    protected MusicDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
      super(context, cancelable, cancelListener);
    }

    @Override
    public void dismiss() {
      activity.getApplicationContext().unregisterReceiver(musicBroadcastReceiver);
      super.dismiss();
    }
  }
}
